package com.roadrunner;

import java.util.ArrayList;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<String>
{
	JsonController mJC = null;
	private static boolean m_bUserConnected = false;
	private static User	m_CurentUser = null;
	private static ArrayList<Job>	m_CurrentUserOrders = null;
	
	private String  currentServerLabel = "CurrentServer";
	public static String 	currentServer = "";
	private String currentServerName = "TIMISOARA";
	private String  m_txtConsole = "";
	
	static final String STATE_SERVER = "currentServer";
	static final String STATE_CONSOLE = "consoleLog";
	
	static final String Dispatcher = "http://192.168.2.112:8080/DISPATCHERRoadRunner/findserver";
			
	
	public static final int JOB_GET_ALL 		= 1;
	public static final int JOB_GET_MY 			= 2;
	public static final int JOB_CHANGE_SRV 		= 3;
	public static final int JOB_CHANGE_Order 	= 4;
	public static final int JOB_UPDATE 			= 5;
	public static final int JOB_SAVE_STATE		= 5;
	
	private SharedPreferences prefs = null;
	
	private static Boolean connected=false;
	
	private static final String tag = MainActivity.class.getName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		String serverResponse = prefs.getString(currentServerLabel, "");
		
		if(serverResponse.length() <= 0)
		{
			Editor editor = prefs.edit();
			editor.putString(currentServerLabel, currentServer);
			editor.commit();
		}
		else
		{
			currentServer = serverResponse;
		}
		
		Bundle b = new Bundle();
		String url = Dispatcher + "?serverlocation="+currentServerName;			
		b.putInt("requestFunction", MainActivity.JOB_CHANGE_SRV);
		b.putString("URL_CALL", url);	     
		MyHttp loader =  (MyHttp) getSupportLoaderManager().initLoader(0, b, this);
		loader.forceLoad(); 
			
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	    // Save the user's current game state
	    savedInstanceState.putString(STATE_SERVER, currentServer);
	    savedInstanceState.putString(STATE_CONSOLE, m_txtConsole);
	    
	    // Always call the superclass so it can save the view hierarchy state
	    super.onSaveInstanceState(savedInstanceState);
	}
	
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	    // Always call the superclass so it can restore the view hierarchy
	    super.onRestoreInstanceState(savedInstanceState);
	   
	    // Restore state members from saved instance
	    currentServer = savedInstanceState.getString(STATE_SERVER);
	    m_txtConsole = savedInstanceState.getString(STATE_CONSOLE);
	    
	    TextView txtServer = (TextView)this.findViewById(R.id.serverName);
		txtServer.append(currentServer);
		
		TextView txtConsole = (TextView)this.findViewById(R.id.console);
		txtConsole.append(m_txtConsole);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}

	private void showLogin()
	{
		setContentView(R.layout.login_layout);
		
		final EditText txtUserName;
		final EditText txtPassword;
		Button btnLogin;
		final Button btnCancel;
		
		txtUserName=(EditText)this.findViewById(R.id.txtUname);
        txtPassword=(EditText)this.findViewById(R.id.txtPwd);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				//here will be to code to send the autentification to server
				//if( (txtUserName.getText().toString().equals("drakedex@gmail.com")) && 	
				//	(txtPassword.getText().toString().equals("alex"))
				//)
				{
					
					setUserConnected(true);	
					String userName 		= "AlexPaun";
					String userAddress 		= "Sinandrei 443";
					String userPhone 		= "0756.320.063";
					String userEmail 		= "drakedex@gmail.com";
					String userOrdersID		= "1,2,3,4";			
					
					m_CurentUser = new User(userName, userAddress, userPhone, userEmail, userOrdersID);
					
					Editor editor = prefs.edit();
					editor.putString("CurrentUser", m_CurentUser.Serialize());
					editor.putString("CurrentUserName", m_CurentUser.getName());
					editor.commit();
					
					showHome();
				}
				
			}
        });
	}
        
	private void showHome()
	{
		setContentView(R.layout.activity_main);
		
		TextView txtServer = (TextView)this.findViewById(R.id.serverName);
		txtServer.append(currentServer);
		
		TextView txtConsole = (TextView)this.findViewById(R.id.console);
		txtConsole.setMovementMethod(new ScrollingMovementMethod());
		Console(m_txtConsole);
	}
	
	private void setupView()
	{
		if(isUserConnected())
		{
			showHome();
		}
		else
		{
			showLogin();
		}
	}
	boolean isUserConnected(){
		return m_bUserConnected;
	}
	
	void setUserConnected(boolean connected){
		m_bUserConnected = connected;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{		
		switch(item.getItemId())
		{
		case R.id.home:
			//Intent homeIntent = new Intent(this, MainActivity.class);
			//homeIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			//startActivity(homeIntent);
			showHome();
			break;
			
		case R.id.my_jobs:
			{
				Intent newIntent = new Intent(this, JobsList.class);
				Bundle args = new Bundle();
	            args.putInt("JOB", JOB_GET_MY);
	            args.putString("USER", m_CurentUser.getName());
	            newIntent.putExtras(args);
				startActivity(newIntent);
			}
			break;
			
		case R.id.jobs_list:
		{
			Intent newIntent = new Intent(this, JobsList.class);
			Bundle args = new Bundle();
            args.putInt("JOB", JOB_GET_ALL);
            newIntent.putExtras(args);
			startActivity(newIntent);
		}
			break;
			
		case R.id.timisoara:
		{			
			if(currentServerName.compareTo("TIMISOARA") != 0)
			{
				currentServerName = "TIMISOARA";
				Bundle b = new Bundle();
				String url = Dispatcher + "?serverlocation="+currentServerName;
						
				b.putInt("requestFunction", MainActivity.JOB_CHANGE_SRV);
				b.putString("URL_CALL", url);
						
					     
				MyHttp loader =  (MyHttp) getSupportLoaderManager().restartLoader(0, b, this);
				loader.forceLoad(); 
			}
		}
			break;
			
		case R.id.bucuresti:
		{
			//String server = "server,ServerBerlin";
			
			if(currentServerName.compareTo("BUCURESTI") != 0)
			{
				
				currentServerName = "BUCURESTI";
				Bundle b = new Bundle();
				String url = Dispatcher + "?serverlocation="+currentServerName;
						
				b.putInt("requestFunction", MainActivity.JOB_CHANGE_SRV);
				b.putString("URL_CALL", url);
						
					     
				MyHttp loader =  (MyHttp) getSupportLoaderManager().restartLoader(0, b, this);
				loader.forceLoad(); 
			}
		}
			break;
			
		case R.id.cluj:
		{				
			if(currentServerName.compareTo("CLUJ") != 0)
			{
				currentServerName = "CLUJ";
				Bundle b = new Bundle();
				String url = Dispatcher + "?serverlocation="+currentServerName;
						
				b.putInt("requestFunction", MainActivity.JOB_CHANGE_SRV);
				b.putString("URL_CALL", url);
						
					     
				MyHttp loader =  (MyHttp) getSupportLoaderManager().restartLoader(0, b, this);
				loader.forceLoad(); 
			}
		}
			break;
			
		case R.id.action_settings:
			break;
			
		case R.id.exit_app:
			onDestroy();
			break;
			
		default:
			break;
			
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		System.exit(0);
	}
	
	public static ArrayList<Job> getUserOrders()
	{
		return m_CurrentUserOrders;
	}
	
	public void Console(String text)
	{
		TextView txtConsole = (TextView)this.findViewById(R.id.console);
		
		if(txtConsole != null)
		{
			txtConsole.append(text+"\n");
		}
	}

	@Override
	public Loader<String> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		MyHttp http = new MyHttp(this, arg1);	
			return http;
	}

	@Override
	public void onLoadFinished(Loader<String> arg0, String arg1) {
		// TODO Auto-generated method stub
		
		if(arg1.length() == 0)
			return;
		
		HandleLoad(arg1);
	}

	private void HandleLoad(String arg1) {
		// TODO Auto-generated method stub
		String [] keys = arg1.split(",");
		String job = keys[0];
		
		
		if(job.compareTo("newServer") == 0)
		{
			String response = keys[1];
			
			currentServer = response;			
			
			Editor editor = prefs.edit();
			editor.putString(currentServerLabel, currentServer);
			editor.commit();
			
			setupView();
		}
		else if(job.compareTo("loginStatus") == 0)
		{
			int i =0;
		}
	}

	@Override
	public void onLoaderReset(Loader<String> arg0) {
		// TODO Auto-generated method stub
		
	}
}
